from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin

from utils.base_model import BaseModel


class UserManage(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, username, password=None, nickname=None, email=None, phone=None, **extra_fields):
        """创建用户"""
        if not username:
            raise ValueError('用户名必填！')
        if not password:
            raise ValueError('密码必填！')
        email = self.normalize_email(email)
        username = self.model.normalize_username(username)
        user = self.model(username=username, email=email, nickname=nickname, phone=phone, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username, password=None, nickname=None, email=None, phone=None, **extra_fields):
        """创建普通用户"""
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(username, password, nickname, email, phone, **extra_fields)

    def create_superuser(self, username, password=None, nickname=None, email=None, phone=None, **extra_fields):
        """创建管理员用户"""
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(username, password, nickname, email, phone, **extra_fields)


class UserModel(AbstractBaseUser, PermissionsMixin, BaseModel):
    """自定义用户模型"""
    username = models.CharField(max_length=20, verbose_name="该账号", help_text="账号", unique=True)
    nickname = models.CharField(max_length=20, verbose_name="昵称", help_text="昵称", blank=True, null=True)
    phone = models.CharField(max_length=20, verbose_name="手机号码", help_text="手机号码", blank=True, null=True)
    email = models.EmailField(verbose_name="邮箱", help_text="邮箱")

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ['email']
    EMAIL_FIELD = 'email'

    objects = UserManage()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    class Meta:
        db_table = "dtp_user"
        verbose_name = "用户"
        verbose_name_plural = verbose_name
